package com.pdool.gate.controller;

import com.pdool.common.constants.Constant;
import com.pdool.gate.domain.dto.LoginResp;
import com.pdool.gate.service.RoleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 角色创角和登录
 */
@RestController
@CrossOrigin(origins = "*")
public class RoleController {
    @Resource
    RoleService roleService;
    @Value("${server.game}")
    private String gameUri;
    @Resource
    RedisTemplate redisTemplate;


    @GetMapping("/login")
    public LoginResp login(@RequestParam(value = "userName") String userName,
                           @RequestParam(value = "pwd") String pwd) {
        LoginResp loginResp = new LoginResp();
        String token = null;
        try {
            token = roleService.roleLogin(userName, pwd);
        } catch (Exception e) {
            String message = e.getMessage();
            loginResp.setError(message);
            return loginResp;
        }

        loginResp.setToken(token);
        String[] split = gameUri.split(Constant.SPLIT_SEMICOLON);
        Map<String,Integer> onlineCount = redisTemplate.opsForHash().entries(Constant.GAME_ONLINE_COUNT);
        String lastGameUri = null;
        for (String s : split) {
            lastGameUri = s;
            Integer orDefault = onlineCount.getOrDefault(s, 0);
            if (orDefault < 2000){
                break;
            }
        }
        loginResp.setGameUri(lastGameUri);
        return loginResp;
    }

    @Deprecated
    @GetMapping("/create")
    public LoginResp create(@RequestParam(value = "userName") String userName,
                            @RequestParam(value = "pwd") String pwd,
                            @RequestParam(value = "head") String head) {
        String token = roleService.create(userName, pwd, head);
        LoginResp loginResp = new LoginResp();
        loginResp.setToken(token);
        loginResp.setGameUri(gameUri);
        return null;
    }
}
